package cn.rongdao.jrkabao.ui.remind.uicomponent;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.mifengkong.frtools.http.request.callback.BaseImpl;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.inputmethod.FRView;
import com.mifengkong.frtools.ui.adapter.recyclerview.FRBaseRecyclerAdapter;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.recyclerview.PtrRecyclerViewUIComponent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.bean.remind.RemindBean;
import cn.rongdao.jrkabao.bean.remind.RemindExportBillBean;
import cn.rongdao.jrkabao.model.remind.RemindExportBillModel;
import cn.rongdao.jrkabao.model.remind.RemindModel;
import cn.rongdao.jrkabao.ui.main.mainfragment.loanfragment.uicomponent.CheckAllProductUIComponent;
import cn.rongdao.jrkabao.ui.remind.AddRemindCreditCardByMailActivity;
import cn.rongdao.jrkabao.ui.remind.RemindDetailsActivity;
import cn.rongdao.jrkabao.ui.remind.RemindMailListActivity;
import cn.rongdao.jrkabao.ui.remind.SelectFromBottomManager;
import cn.rongdao.jrkabao.ui.remind.adapter.RemindAdapter;
import cn.rongdao.jrkabao.ui.remind.adapter.RemindViewHolder;
import cn.rongdao.jrkabao.ui.remind.event.DeleteCardEvent;
import cn.rongdao.jrkabao.ui.remind.event.MoXieLooperEvent;
import cn.rongdao.jrkabao.ui.remind.event.MoXieSuccessByExportEvent;
import cn.rongdao.jrkabao.ui.remind.event.MoXieSuccessByUpdateEvent;
import cn.rongdao.jrkabao.ui.remind.event.RemindChangeStatusSuccessEvent;
import cn.rongdao.jrkabao.ui.remind.event.SaveCardEvent;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.LoginUtil;
import cn.rongdao.jrkabao.util.moxie.MoXieManager;
import cn.rongdao.jrkabao.widget.SelectPaymentWayFromBottom;

/**
 * Created by jack on 2017/9/8
 */

public class RemindUIComponent extends LinearLayout implements FRBaseRecyclerAdapter.OnItemClickListener<RemindViewHolder> {

    public RemindUIComponent(Context context) {
        super(context);
    }

    public RemindUIComponent(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RemindUIComponent(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    RemindDetailsTitleBarUIComponent titleBarUIComponent;
    private PtrRecyclerViewUIComponent ptrRecyclerViewUIComponent;
    private RemindAdapter remindAdapter;
    private RecyclerAdapterWithHF mAdapter;
    private CheckAllProductUIComponent viewFooter;
    private RelativeLayout rlTip;
    private TextView tvTip;
    private ImageView ivTipClose;
    private MoXieManager moXieManager;

    private BaseImpl baseImpl;
    private int jumpStatus;
    private String jumpEmail;
    private boolean isUpdate;   //是更新数据还是添加数据(魔蝎)
    private boolean isMoXieExportIng = false;
    private SelectFromBottomManager selectFromBottomManager;
    private int itemClickPosition;
    private String email;

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        EventBus.getDefault().register(this);
        titleBarUIComponent = (RemindDetailsTitleBarUIComponent) findViewById(R.id.lr_titlebar);
        ptrRecyclerViewUIComponent = (PtrRecyclerViewUIComponent) findViewById(R.id.lr_ptrframelayout);
        ptrRecyclerViewUIComponent.setRecyclerViewOverScrollModeNever();
        rlTip = (RelativeLayout) findViewById(R.id.lr_rl_tip);
        tvTip = (TextView) findViewById(R.id.lr_tv_tip);
        ivTipClose = (ImageView) findViewById(R.id.lr_iv_close);
        viewFooter = FRView.inflateLayout(getContext(), R.layout.layout_loan_footer_view);

        initTitleBar();
    }

    private void initListener() {
        ptrRecyclerViewUIComponent.setCanRefresh(false);
        viewFooter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!LoginUtil.isLogin(getContext())) {
                    return;
                }
                AddRemindCreditCardByMailActivity.start(getContext());
            }
        });

        ivTipClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rlTip.setVisibility(GONE);
            }
        });

        remindAdapter.setOnRemindItemClickListener(new RemindViewHolder.OnRemindItemClickListener() {
            @Override
            public void checkBalance(int position) {
                itemClickPosition = position;
                selectFromBottomManager.showCheckBalancePop(remindAdapter.getDataList().get(position).getIs_export());
            }

            @Override
            public void repayment(int position) {
                itemClickPosition = position;
                String buttonStatus = remindAdapter.getDataList().get(position).getButton_status();
                if (remindAdapter.getDataList().get(position).isExample()) {
                    FRToast.showToastSafe("不妨添加信用卡试试");
                    return;
                }
                if (buttonStatus.equals("2")) {
                    isUpdate = CommonUtil.isStatusSuccess(remindAdapter.getDataList().get(position).getIs_export());
                    moXieManager.startMoXieWithEmail(remindAdapter.getDataList().get(position).getEmail());
                    return;
                }
                selectFromBottomManager.showPaymentPop(buttonStatus);
            }
        });

        selectFromBottomManager.setOnCheckBalanceClickListener(new SelectPaymentWayFromBottom.OnCheckBalanceClickListener() {
            @Override
            public void emailCheck() {
                moXieManager.startMoXieWithEmail(remindAdapter.getDataList().get(itemClickPosition).getEmail());
                selectFromBottomManager.dismissCheckBalancePop();
            }

            @Override
            public void msgCheck() {
                selectFromBottomManager.remindAmountQuery(baseImpl, remindAdapter.getDataList().get(itemClickPosition).getId());
            }
        });

        selectFromBottomManager.setOnSelectListener(new SelectPaymentWayFromBottom.OnSelectListener() {
            @Override
            public void onSelect(boolean isSelected) {
                selectFromBottomManager.remindChangeRepayStatus(baseImpl, remindAdapter.getDataList().get(itemClickPosition).getId(), isSelected);
            }
        });

        selectFromBottomManager.setOnChangeRepayStatusListener(new SelectFromBottomManager.OnChangeRepayStatusListener() {
            @Override
            public void onChangeRepayStatusSuccess() {
                selectFromBottomManager.dismissPaymentPop();
                setAdapterData();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void saveCardMessage(SaveCardEvent saveCardEvent) {
        setAdapterData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void deleteCardMessage(DeleteCardEvent deleteCardEvent) {
        setAdapterData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void MoXieSuccessByUpdateEventMessage(MoXieSuccessByUpdateEvent moXieSuccessByUpdateEvent) {
        startMoXieLooper(true, moXieSuccessByUpdateEvent.getEmail(), true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void MoXieSuccessByExportMessage(MoXieSuccessByExportEvent moXieSuccessByExportEvent) {
        startMoXieLooper(false, moXieSuccessByExportEvent.getEmail(), true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void MoXieLooperSuccessMessage(MoXieLooperEvent moXieLooperEvent) {
        setAdapterData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void RemindChangeStatusSuccessMessage(RemindChangeStatusSuccessEvent remindChangeStatusSuccessEvent) {
        setAdapterData();
    }

    public void initPtr(BaseImpl baseImpl) {
        this.baseImpl = baseImpl;
        selectFromBottomManager = new SelectFromBottomManager((Activity) getContext());
        remindAdapter = new RemindAdapter(getContext(), this);
        mAdapter = new RecyclerAdapterWithHF(remindAdapter);
        ptrRecyclerViewUIComponent.setProgressStyle();
        ptrRecyclerViewUIComponent.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter.addFooter(viewFooter);
        ptrRecyclerViewUIComponent.setAdapter(mAdapter);
        moXieManager = new MoXieManager(baseImpl);
        moXieManager.initKaMaoMoXie();
        setAdapterData();
        initListener();
        initMoXieListener();
    }

    private void initMoXieListener() {
        moXieManager.setOnMoXieReturnListener(new MoXieManager.OnMoXieReturnListener() {
            @Override
            public void looperMethod(String email) {
                if (!FRString.isEmpty(email)) {
                    RemindUIComponent.this.email = email;
                }
                getMoXieStatusData();
            }

            @Override
            public void successReturn(String email) {
                isMoXieExportIng = true;
                startMoXieLooper(isUpdate, email, false);
            }
        });
    }

    public void initMoXie() {
        moXieManager.initKaMaoMoXie();
    }

    private void getMoXieStatusData() {
        RemindExportBillModel.getInstance().execute(isUpdate, email, new FRBaseObserver<RemindExportBillBean>(baseImpl) {
            @Override
            protected void onBaseNext(RemindExportBillBean data) {
                if (CommonUtil.isStatusSuccess(data.getExport_status())) {
                    finishMoXieExport();
                    setAdapterData();

                }
            }

            @Override
            protected void onBaseError(Throwable t) {
                super.onBaseError(t);
                finishMoXieExport();
            }
        });
    }

    private void finishMoXieExport() {
        moXieManager.onStop();
        titleBarUIComponent.clearAnim();
        isMoXieExportIng = false;
        rlTip.setVisibility(GONE);
    }

    private void startMoXieLooper(boolean isUpdate, String email, boolean isEventBus) {
        this.isUpdate = isUpdate;
        this.email = email;
        setTip("邮箱账单导入中，请稍候...");
        titleBarUIComponent.startAnim();
        if (isEventBus) {
            moXieManager.startRun(false);
        }
    }

    private void initTitleBar() {
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
        titleBarUIComponent.setTitleContent("卡管理");
        titleBarUIComponent.setOnRefreshClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!LoginUtil.isLogin(getContext())) {
                    return;
                }
                if (isMoXieExportIng) {
                    FRToast.showToastSafe("数据获取中，请稍候再试...");
                    return;
                }
                if (remindAdapter.getDataList().size() > 0 && remindAdapter.getDataList().get(0).isExample()) {
                    FRToast.showToastSafe("不妨添加信用试试");
                    return;
                }
                if (CommonUtil.isStatusSuccess(jumpStatus)) {  //邮箱列表
                    RemindMailListActivity.start(getContext());
                    return;
                }
                isUpdate = false;
                moXieManager.startMoXieWithEmail(jumpEmail);
            }
        });
    }

    public void setAdapterData() {
        if (LoginUtil.isLogin()) {
            RemindModel.getInstance().execute(new FRBaseObserver<RemindBean>(baseImpl,"加载中，请稍候...") {
                @Override
                protected void onBaseNext(RemindBean data) {
                    if (null != data) {
                        if (null != data.getEmail_status()) {
                            jumpStatus = data.getEmail_status().getJump_status();
                            jumpEmail = data.getEmail_status().getEmail();
                        }
                        setAdapterDataList(data.getList());
                    } else {
                        setAdapterDataList(null);
                    }
                }

                @Override
                protected void onBaseError(Throwable t) {
                    super.onBaseError(t);
                    setAdapterDataList(null);
                }
            });
        } else {
            setAdapterDataList(null);
        }
    }


    private void setAdapterDataList(List<RemindBean.RemindBankList> dataList) {
        if (null != dataList && dataList.size() > 0) {
            remindAdapter.setDataList(dataList);
        } else {
            remindAdapter.setDataList(remindAdapter.getExampleList());
        }
        viewFooter.setAddCardContent("+ 添加新的信用卡");
        mAdapter.notifyDataSetChanged();
    }

    public void setTitleBarLeftOnClickListener() {
        titleBarUIComponent.initLeftBack();
    }

    @Override
    public void onItemClick(RemindViewHolder remindViewHolder, int position) {
        if (!LoginUtil.isLogin(getContext())) {
            return;
        }
        RemindDetailsActivity.start(getContext(), remindAdapter.getDataList().get(position).getId());
    }

    public void setTip(String tip) {
        rlTip.setVisibility(VISIBLE);
        tvTip.setText(FRString.valueOf(tip));
    }

    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (null!=moXieManager){
            moXieManager.onDestroy();
        }
    }
}